'use strict';
const provinces = require('../helper/cities');
const barcode = require('barcode');
const moment = require('moment');
const path = require('path');
const fs = require('fs');
const request = require('request');
const { type } = require('os');


async function writeFile(imgPath, writeStream) {
    const readStream = request(imgPath).pipe(writeStream);
    return new Promise((fulfill) => {
        readStream.on("finish", function () {
            writeStream.end();
            fulfill();
        });
    });
}


function deleteall(path) {
    var files = [];
    if (fs.existsSync(path)) {
        files = fs.readdirSync(path);
        files.forEach(function (file, index) {
            var curPath = path + "/" + file;
            if (fs.statSync(curPath).isDirectory()) {
                deleteall(curPath);
            } else {
                fs.unlinkSync(curPath);
            }
        });
        fs.rmdirSync(path);
    }
};

module.exports = app => {

    class ApiController extends app.Controller {

        async bind(ctx, next) {
            ctx.body = {
                code: 0,
                data: 'from server'
            };
        }

        async smsSend(ctx, next) {
            const { mobilePhone } = await ctx.parseBody();
            const r = await ctx.api.portal.postSms({ mobilePhone });
            ctx.body = {
                code: 0,
                data: r
            };
        }

        // 验证手机验证码
        async verifyPatient(ctx, next) {
            const { mobilePhone, code } = await ctx.parseBody();
            // r 为会员id
            const r = await ctx.api.portal.verifyPatient({ mobilePhone, code });
            ctx.body = {
                code: 0,
                data: r,
            }
        }

        async getPatientDrugs(ctx, next) {
            const { patientId } = ctx.params;
            const { search, skip, limit } = ctx.query;
            const r = await ctx.api.portal.getPatientDrugs(patientId, { search, skip, limit });
            ctx.body = {
                code: 0,
                data: r,
            }
        }

        async verifyOrder(ctx, next) {
            const { patientId } = ctx.params;
            const { diseasesIds, period, drugs } = await ctx.parseBody();
            const r = await ctx.api.portal.verifyOrder(patientId, { diseasesIds, period, drugs });
            ctx.body = {
                code: 0,
                data: {
                    verifyMessage: r
                }
            }
        }

        async postOrder(ctx, next) {
            const { patientId } = ctx.params;
            const result = await ctx.api.portal.postOrder(patientId, await ctx.parseBody());
            ctx.body = {
                code: 0,
                data: result
            }
        }
        async postOrderNoRule(ctx, next) {
            const { patientId } = ctx.params;
            const result = await ctx.api.portal.postOrderNoRule(patientId, await ctx.parseBody());
            ctx.body = {
                code: 0,
                data: result
            }
        }

        async getOrder(ctx, next) {
            const res = ctx.params
            const res1 = ctx.query;
            const result = await ctx.api.portal.getOrder(res, res1);
            ctx.body = {
                code: 0,
                data: result
            }
        }

        async bindPatient(ctx, next) {
            const patientId = ctx.params.patientId;
            const openId = ctx.weixin.openId;
            // const wx = await ctx.api.bind.getWeixinInfo(app.config.weixin.appId);
            // const bindCheck = await ctx.api.portal.isBinding(patientId, wx.label);
            // if (!bindCheck.isBinding) {
            //     ctx.body = {
            //         code: 1,
            //         message: '该会员所属区域与当前公众号服务区域不匹配，请关注正确的公众号或联系MA转签。'
            //     }
            //     return;
            // }
            const r = await ctx.api.bind.bindPatient(patientId, openId);
            ctx.body = {
                code: 0,
                data: r,
            }
        }

        async hospital(ctx, next) {
            const query = ctx.query;
            const { where, skip, limit, location } = ctx.query;
            const r = await ctx.api.portal.getHospital({ where, skip, limit, nearBy: location });
            ctx.body = {
                code: 0,
                data: r,
            }
        }

        async druglist(ctx, next) {
            const { skip, limit, search, patientId } = ctx.query;
            const hospitalId = ctx.params.hospitalId;
            const r = await ctx.api.portal.getDrugList(hospitalId, { skip, limit, search, patientId });
            ctx.body = {
                code: 0,
                data: r,
            }
        }

        async drugDetail(ctx, next) {
            const hospitalId = ctx.params.hospitalId;
            const drugId = ctx.params.drugId;
            const r = await ctx.api.portal.getDrugDetail(hospitalId, drugId);
            ctx.body = {
                code: 0,
                data: r,
            }
        }

        async address(ctx, next) {
            const query = ctx.query;
            let r;
            if (query.provinceId) {
                if (query.cityId) {
                    const cities = provinces.find(item => item.id === query.provinceId).cities;
                    r = cities.find(item => item.id === query.cityId).areas.map(o => ({
                        id: o.id,
                        name: o.name,
                    }));
                } else {
                    const city = provinces.find(item => item.id === query.provinceId).cities;
                    r = city.map(o => ({
                        id: o.id,
                        name: o.name,
                    }))
                }
            } else {
                r = provinces.map(item => ({
                    id: item.id,
                    name: item.name,
                }))
            }
            ctx.body = {
                code: 0,
                data: r,
            }
        }

        async geocode(ctx, next) {
            const addr = await app.baiduMap.reverseGeocoder({
                location: `${ctx.query.latitude},${ctx.query.longitude}`,
                coordtype: 'gcj02ll',
            });
            let r = null;
            if (addr && addr.addressComponent) {
                if (addr.addressComponent.country_code === 0) {
                    const pn = addr.addressComponent.province;
                    const cn = addr.addressComponent.city;
                    const dn = addr.addressComponent.district;
                    let p = provinces.find(p => p.name === pn);
                    let c;
                    let d;
                    if (p) {
                        c = p.cities.find(c => c.name === cn);
                    }
                    if (c) {
                        d = c.areas.find(d => d.name === dn);
                    }
                    if (!p) {
                        p = {
                            id: '990000',
                            name: pn,
                        };
                    }
                    if (!c) {
                        c = {
                            id: '999900',
                            name: cn
                        };
                    }
                    if (!d) {
                        d = {
                            id: '999999',
                            name: dn
                        };
                    }
                    r = {
                        provinceId: p.id,
                        provinceName: p.name,
                        cityId: c.id,
                        cityName: c.name,
                        areaId: d.id,
                        areaName: d.name
                    };
                }
            }
            ctx.body = {
                code: 0,
                data: r
            };
        }

        async barcode(ctx) {
            ctx.body = await new Promise((fulfill, reject) => {
                const img = barcode('code128', {
                    data: ctx.query.text,
                    width: Number(ctx.query.width),
                    height: Number(ctx.query.height),
                });
                img.getStream(function (err, readStream) {
                    if (err) {
                        reject(err);
                        return;
                    }
                    fulfill(readStream);
                });
            });
        }

        async qiyuUserInfo(ctx, next) {
            const { userid } = await ctx.parseBody();
            const patientId = await ctx.api.bind.getBindPatientByWeixin(userid);
            let r;
            if (patientId) {
                const SEX = {
                    0: '女',
                    1: '男',
                }
                const info = await ctx.api.portal.getPatientInfo(patientId);
                r = [{
                    "index": 0,
                    "key": "name",
                    "label": "姓名",
                    "value": info.name,
                }, {
                    index: 1,
                    key: 'sex',
                    label: '性别',
                    value: SEX[info.sex],
                }, {
                    "index": 2,
                    "key": "age",
                    "label": "年龄",
                    "value": info.birthday && (new Date().getFullYear()) - info.birthday.slice(0, 4),
                },
                {
                    "index": 3,
                    "key": "diseases",
                    "label": "现有疾病",
                    "value": info.diseases && info.diseases.map(o => o.name).join(','),
                },
                {
                    "index": 4,
                    "key": "hospital",
                    "label": "服务机构查询",
                    "value": info.hospital && info.hospital.name,
                },
                {
                    "index": 5,
                    "key": "tags",
                    "label": "标签",
                    "value": info.tags && info.tags.map(o => o.name).join(','),
                },
                {
                    "index": 6,
                    "key": "registerDrugs",
                    "label": "登记用药",
                    "value": "登记用药",
                    "href": `${app.config.crm.webUrl}/?modal=createOrder&modalParam=${patientId}&channel=12`
                }
                ]
            } else {
                r = [{
                    "index": 0,
                    "key": "bind",
                    "label": "客户未绑定",
                    "value": "请绑定账号",
                    "href": `${app.config.crm.webUrl}/weixin/bind?openid=${userid}&appid=${app.config.weixin.appId}`
                }];
            }
            ctx.body = {
                rlt: 0,
                data: r,
            }
        }

        async qiyuUserOrder(ctx, next) {
            const { userid } = await ctx.parseBody();
            const patientId = await ctx.api.bind.getBindPatientByWeixin(userid);
            let r = [];
            if (patientId) {
                const STATUS = {
                    10: '初始订单',
                    20: '患者已确认',
                    30: '医生已确认',
                    35: '药师已确认',
                    40: '备药中',
                    45: '配送中',
                    50: '待取药',
                    60: '已取药',
                    70: '正在使用',
                    97: '药师已驳回',
                    98: '撤单',
                    99: '完成',
                };
                const order = await ctx.api.portal.getPatientOrder(patientId);
                r = order.list.map((item, index) => ({
                    index,
                    blocks: [
                        {
                            index: 0,
                            is_title: true,
                            data: [
                                { index: 0, key: 'time', label: '', value: moment(item.createDate).format('YYYY-MM-DD') }
                            ]
                        },
                        {
                            index: 1,
                            data: [
                                { index: 0, key: 'orderNo', label: '订单号', value: item.orderNo },
                                { index: 1, key: 'status', label: '订单状态', value: STATUS[item.status] },
                                {
                                    index: 2, key: 'drugs', label: '药品信息',
                                    value: item.drugs.map(
                                        (drug, idx) => `${idx + 1}，${drug.commonName}(${drug.productName})${drug.preparationUnit}*${drug.packageSize}${drug.minimumUnit}/${drug.packageUnit}*${drug.amount}${drug.packageUnit}`
                                    ).join('。')
                                },
                            ]
                        },
                    ]
                }))
            }
            ctx.body = {
                rlt: 0,
                count: r.length,
                orders: r,
            }
        }

        async jsApiConfig(ctx) {
            const body = await ctx.parseBody();
            const config = await ctx.api.bind.callWeixinApi('getJsConfig', {
                debug: app.config.weixin.debug,
                jsApiList: JSON.parse(body.jsApiList),
                url: body.url
            });
            ctx.body = {
                code: 0,
                data: config
            };
        }

        async getUserInfo(ctx) {
            const r = await ctx.api.portal.getUserInfo();
            ctx.body = {
                code: 0,
                data: r
            }
        }

        async getDoctors(ctx) {
            const hospitalId = ctx.params.hospitalId;
            const r = await ctx.api.portal.getDoctors(hospitalId);
            ctx.body = {
                code: 0,
                data: r
            }
        }

        async getPackages(ctx) {
            const { where, skip, limit } = ctx.query;
            const r = await ctx.api.portal.getPackages({ where, skip: skip || 0, limit })
            ctx.body = {
                code: 0,
                data: r
            }
        }

        async getPatientDetail(ctx) {
            const patientId = ctx.params.patientId;
            const r = await ctx.api.portal.getPatientDetail(patientId);
            ctx.body = {
                code: 0,
                data: r
            }
        }

        async getOrders(ctx) {
            const { where, skip, limit } = ctx.query;
            const r = await ctx.api.portal.getOrders({ where, skip, limit });
            ctx.body = {
                code: 0,
                data: r,
            }
        }

        async cancelReason(ctx) {
            const orderId = ctx.params.orderId;
            const { reasonId, remarks, operatorUserName } = await ctx.parseBody()
            const r = await ctx.api.portal.cancelReason(orderId, { reasonId, remarks, operatorUserName });
            ctx.body = {
                code: 0,
                data: r,
            }
        }

        async getOrderLogs(ctx) {
            const patientId = ctx.params.patientId;
            const r = await ctx.api.portal.getOrderCancelReason(orderId, data);
            ctx.body = {
                code: 0,
                data: r,
            }
        }

        async localHospital(ctx, next) {
            const { skip, limit, location } = ctx.query;
            const wx = await ctx.api.bind.getWeixinInfo(app.config.weixin.appId);
            const where = {
                weixinLabel: wx.label,
                status: 0,
            }
            const r = await ctx.api.portal.getHospital({ where, skip, limit, nearBy: location });
            ctx.body = {
                code: 0,
                data: r,
            }
        }

        async potentialPatients(ctx) {
            const potentialPatients = await ctx.parseBody();
            potentialPatients.diseases = potentialPatients.diseases ? JSON.parse(potentialPatients.diseases) : null;
            const result = await ctx.api.portalJson.potentialPatients(potentialPatients);
            ctx.body = {
                code: 0,
                data: result
            }
        }
        async activeMobileVerify(ctx) {
            const { activityId } = ctx.query;
            const { mobilePhone } = ctx.params;
            const result = await ctx.api.portal.activeMobileVerify(mobilePhone, activityId);
            ctx.body = {
                code: 0,
                data: result
            }
        }

        async getContactNo(ctx) {
            const wx = await ctx.api.bind.getWeixinInfo(app.config.weixin.appId);
            const contactNo = await ctx.api.portal.getConfigurations(wx.label, 2);
            ctx.body = {
                code: 0,
                data: contactNo,
            }
        }

        async checkBindPatients(ctx) {
            try {
                const result = await ctx.api.portal.getPatientsAvailable(ctx.query);
                if (result) {
                    // const wx = await ctx.api.bind.getWeixinInfo(app.config.weixin.appId);
                    // console.log('wx', wx);
                    // const binds = await ctx.api.bind.getBindWeixinByPatient(wx);
                    // if (binds) {
                    //     ctx.body = {
                    //         code: 3,
                    //         message: '该手机号已存在且已开通微信服务，登录后仅可在此微信号下使用PBM服务。',
                    //     }
                    //     return;
                    // }
                    ctx.body = {
                        code: 0,
                    }
                    return
                } else {
                    ctx.body = {
                        code: 2,
                    }
                    return;
                }
            } catch (e) {
                console.log('checkBindPatients', e);
            }

        }

        async checkSignPatients(ctx) {
            try {
                const result = await ctx.api.portal.getPatientsAvailable(ctx.query);
                if (result) {
                    ctx.body = {
                        code: 0,
                        data: { patientId: result },
                    }
                    return;

                } else {
                    ctx.body = {
                        code: 0,
                    }
                    return;
                }
            } catch (e) {
                console.log('checkSignPatients', e);
            }

        }

        //发送验证码
        async userSendCode(ctx, next) {
            const { mobilePhone } = await ctx.parseBody();
            const r = await ctx.api.portal.userSendCode({ mobilePhone });
            ctx.body = {
                code: 0,
                data: r
            };
        }
        async userRegister(ctx) {
            const user = await ctx.parseBody();
            if (user.address) {
                user.address = JSON.parse(user.address);
            }
            if (user.diseases) {
                user.diseases = JSON.parse(user.diseases);
            }
            const r = await ctx.api.portalJson.userRegister(user);
            ctx.body = {
                code: 0,
                data: r
            };
        }
        async perfectInformation(ctx) {
            const user = await ctx.parseBody();
            if (user.address) {
                user.address = JSON.parse(user.address);
            }
            if (user.diseases) {
                user.diseases = JSON.parse(user.diseases);
            }
            try {
                const r = await ctx.api.portalJson.perfectInformation(user);
                ctx.body = {
                    code: 0,
                    data: r
                };
            } catch (error) {
                ctx.body = {
                    code: error.code,
                    message: error.message,
                    data: error.data,
                }
            }
        }

        async getPatientNewInfo(ctx) {
            const result = await ctx.api.portal.getPatientNewInfo(ctx.query)
            ctx.body = {
                code: 0,
                data: result,
            }
        }

        async shareNewPage(ctx) {
            const wx = await ctx.api.bind.getWeixinInfo(app.config.weixin.appId);
            ctx.body = {
                code: 0,
                data: wx.label,
            }
        }

        async shareNewCode(ctx) {
            const result = await ctx.api.bind.getQrCode(ctx.query);
            ctx.body = {
                code: 0,
                data: result,
            }
        }

        async getPatientHos(ctx) {
            const wx = await ctx.api.bind.getWeixinInfo(app.config.weixin.appId);
            ctx.body = {
                code: 0,
                data: wx.ownerCompany,
            }
        }

        async getInsurances(ctx) {
            const insurances = await ctx.api.portal.getInsurances();
            ctx.body = {
                code: 0,
                data: insurances,
            }
        }
        async getDiseases(ctx) {
            const diseases = await ctx.api.portal.getDiseases();
            ctx.body = {
                code: 0,
                data: diseases,
            }
        }
        async getRegions(ctx) {
            const regions = await ctx.api.portal.getRegions(ctx.query);
            ctx.body = {
                code: 0,
                data: regions,
            }
        }

        async getPatientInfo(ctx) {
            try {
                const { patientId } = ctx.params;
                const patient = await ctx.api.portal.getPatientInfo(patientId);
                ctx.body = {
                    code: 0,
                    data: patient,
                }
            } catch (error) {
                ctx.logger.error('[CreatInsuranceOrder ERROR]', error);
                ctx.body = {
                    code: error.code,
                    message: error.message,
                    data: error.data,
                }
            }
        }

        async openInfo(ctx) {
            const openInfo = await ctx.api.portal.openInfo();
            ctx.body = {
                code: 0,
                data: openInfo,
            }
        }
        async getAllUrl(ctx) {
            let webUrl = app.config.weixin.webUrl;
            const wx = await ctx.api.bind.getWeixinInfo(app.config.weixin.appId);
            const PBMViewDefault = "http://www.wanhuhealth.com/%E4%B8%87%E6%88%B7%E4%B8%9A%E5%8A%A1/%E4%B8%87%E6%88%B7%E5%81%A5%E5%BA%B7pbm%E6%A8%A1%E5%BC%8F/";
            let PBMView;
            try {
                PBMView = await ctx.api.portal.getConfigurations(wx.label, 1);
            } catch (e) {
                ctx.logger.error('weixin-getConfigurations error ', e);
                PBMView = null;
            }
            if (webUrl[webUrl.length - 1] === '/') {
                webUrl = webUrl.substr(0, webUrl.length - 1);
            }
            const allUrl = [
                {
                    "type": "view",
                    "name": "服务网点",
                    "url": `${webUrl}/hospitals`
                },
                {
                    "type": "view",
                    "name": "PBM福利计划",
                    "url": `${PBMView || PBMViewDefault}`
                },
                {
                    "type": "view",
                    "name": "药品目录",
                    "url": process.env.DRUG_LIST_HOSPITAL_ID ? `${webUrl}/hd/${process.env.DRUG_LIST_HOSPITAL_ID}` : `${webUrl}/drugs`
                },
                {
                    "type": "view",
                    "name": "拉新有礼",
                    "url": `${webUrl}/newShare`
                },
                {
                    "type": "view",
                    "name": "万户宝",
                    "url": `${webUrl}/shareToOther`
                }
            ]
            ctx.body = {
                code: 0,
                data: allUrl
            }
        }

        // 找药
        async getNewDrugList(ctx) {
            console.log('getNewDrugList')
            const result = await ctx.api.portal.getNewDrugList(ctx.query);
            console.log('getNewDrugList result:', result)
            ctx.body = {
                code: 0,
                data: result,
            }
        }

        // 社区目录
        async getHosDrugDetail(ctx) {
            const result = await ctx.api.portal.getHosDrugDetail(ctx.query);
            ctx.body = {
                code: 0,
                data: result,
            }
        }
        // 基础目录
        async getBasisDrugDetail(ctx) {
            const result = await ctx.api.portal.getBasisDrugDetail(ctx.query);
            ctx.body = {
                code: 0,
                data: result,
            }
        }

        // 查询需求单
        async queryDemandList(ctx) {
            const result = await ctx.api.portal.queryDemandList(ctx.query);
            ctx.body = {
                code: 0,
                data: result,
            }
        }

        // 添加需求单
        async addDrugToDemand(ctx) {
            const data = await ctx.parseBody();
            const result = await ctx.api.portal.addDrugToDemand(data);
            ctx.body = {
                code: 0,
                data: result,
            }
        }

        // 添加需求单
        async updateDrugToDemand(ctx) {
            const data = await ctx.parseBody();
            const { patientId, formId } = ctx.params;
            const result = await ctx.api.portal.updateDrugToDemand(patientId, formId, data);
            ctx.body = {
                code: 0,
                data: result,
            }
        }
        // 查询绿A开通信息
        async getAopenInfo(ctx) {
            const result = await ctx.api.portal.getAopenInfo()
            ctx.body = {
                code: 0,
                data: result,
            }
        }

        async getOrderPatientInfo(ctx) {
            const patient = await ctx.api.portal.getPatientInfo(ctx.query.patientId);
            ctx.body = await ctx.indexPage('', {
                mount: {
                    medicineHomePage: {
                        patient,
                    }
                }
            });
        }

        async uploadImages(ctx) {
            const body = await ctx.parseBody();
            const data = await ctx.api.portal.uploadImages(body);
            ctx.body = {
                code: 0,
                data: data,
            }
        }

        async getPoint(ctx) {
            const { patientId } = ctx.params;
            const regions = await ctx.api.portal.getPoint(patientId);
            ctx.body = {
                code: 0,
                data: regions,
            }
        }
        async getPointRecord(ctx) {
            const { patientId } = ctx.params;
            const regions = await ctx.api.portal.getPointRecord(patientId, ctx.query);
            ctx.body = {
                code: 0,
                data: regions,
            }
        }
        async checkPatient(ctx) {
            const patientId = await ctx.api.bind.getBindPatientByWeixin(ctx.weixin.openId);
            ctx.body = {
                code: 0,
                data: patientId,
            }
        }

        async receiverAddress(ctx) {
            const { patientId } = ctx.params;
            const query = ctx.query;
            const address = await ctx.api.portal.receiverAddress(patientId, query);
            ctx.body = {
                code: 0,
                data: address,
            }
        }

        async addReceiverAddress(ctx) {
            const { patientId } = ctx.params;
            const body = await ctx.parseBody();
            const address = await ctx.api.portal.addReceiverAddress(patientId, body);
            ctx.body = {
                code: 0,
                data: address,
            }
        }

        async updateReceiverAddress(ctx) {
            const { patientId, id } = ctx.params;
            const body = await ctx.parseBody();
            const address = await ctx.api.portal.updateReceiverAddress(patientId, id, body);
            ctx.body = {
                code: 0,
                data: address,
            }
        }

        async deleteReceiverAddress(ctx) {
            const { patientId, id } = ctx.params;
            const address = await ctx.api.portal.deleteReceiverAddress(patientId, id);
            ctx.body = {
                code: 0,
                data: address,
            }
        }

        // 获取一键续订
        async queryOrderCommonList(ctx) {
            const { patientId } = ctx.query;
            const result = await ctx.api.portal.queryOrderCommonList(patientId)
            ctx.body = {
                code: 0,
                data: result,
            }
        }

        async currentPatient(ctx) {
            const patientId = await ctx.api.bind.getBindPatientByWeixin(ctx.weixin.openId);
            if (!patientId) {
                ctx.body = {
                    code: 0,
                    data: null,
                }
                return;
            }
            const info = await ctx.api.portal.getPatientInfo(patientId);
            ctx.body = {
                code: 0,
                data: { ...info, id: patientId },
            }
        }

        async currentWeixinUser(ctx) {
            const user = await ctx.api.bind.getWeixinUserInfo(ctx.weixin.openId);
            ctx.body = {
                code: 0,
                data: user,
            }
        }

        async rewardpoints(ctx) {
            const { patientId } = ctx.params;
            const data = await ctx.api.portal.rewardpoints(patientId);
            ctx.body = {
                code: 0,
                data,
            }
        }

        async welfare(ctx) {
            const { patientId } = ctx.params;
            const { pointsDeductionAmount, drugs } = await ctx.parseBody();
            const data = await ctx.api.portal.welfare(patientId, { pointsDeductionAmount, drugs: JSON.parse(drugs), freight: '' });
            ctx.body = {
                code: 0,
                data,
            }
        }

        async defaultStoreAddress(ctx) {
            const { patientId } = ctx.params;
            const data = await ctx.api.portal.defaultStoreAddress(patientId);
            ctx.body = {
                code: 0,
                data,
            }
        }

        async updateDefaultStoreAddress(ctx) {
            const { patientId } = ctx.params;
            const data = await ctx.api.portal.updateDefaultStoreAddress(patientId, await ctx.parseBody());
            ctx.body = {
                code: 0,
                data,
            }
        }
        async getPatientFreight(ctx) {
            const { patientId } = ctx.params;
            const data = await ctx.api.portal.getPatientFreight(patientId, ctx.query);
            ctx.body = {
                code: 0,
                data,
            }
        }

        async getInsuranceProducts(ctx) {
            const { insurancePackageId } = ctx.params;
            const data = await ctx.api.portal.getInsuranceProducts(insurancePackageId);
            //为了修改C端没有协议不显示的问题，这里增加一个字段
            data.map(item => {
                item.insurancePackageSpecs.map((el, index) => {
                    if (el.type === 101) {
                        item.isShow = true;
                    };
                })
            })
            ctx.body = {
                code: 0,
                data,
            }
        }

        async getServiceArticleList(ctx) {
            const { packageId } = ctx.params;
            const data = await ctx.api.portal.getServiceArticleList(packageId);
            ctx.body = {
                code: 0,
                data,
            }
        }

        async getInsuranceDiseaseInquiriesVersion2(ctx) {
            const { insurancePackageId } = ctx.params;
            const data = await ctx.api.bind.getInsuranceDiseaseInquiries(insurancePackageId);
            ctx.body = {
                code: 0,
                data,
            }
        }
        async getInsuranceDiseaseInquiries(ctx) {
            const { insurancePackageId } = ctx.params;
            const data = await ctx.api.portal.getInsuranceDiseaseInquiries(insurancePackageId);
            ctx.body = {
                code: 0,
                data,
            }
        }
        async creatInsuranceOrder(ctx) {
            const body = await ctx.parseBody();
            try {
                const data = await ctx.api.portal.creatInsuranceOrder({
                    ...body,
                    openId: ctx.weixin.openId,
                    appId: app.config.weixin.appId,
                });
                ctx.logger.info('[CreatInsuranceOrder success]', data);
                ctx.body = {
                    code: 0,
                    data,
                }
            } catch (error) {
                ctx.logger.error('[CreatInsuranceOrder ERROR]', error);
                ctx.body = {
                    code: error.code,
                    message: error.message,
                    data: error.data,
                }
            }
        }
        
        async createMedicineOrder(ctx) {
            let body = await ctx.parseBody();
            let requestArr = []
            for (let key in body) {
                let request = body[key]
                let jsonRequest = JSON.parse(request)
                request = { ...jsonRequest }
                requestArr.push(request)
            }

            try {
                const data = await ctx.api.portalJson.createMedicineOrder(ctx.params.orderId, requestArr);
                ctx.logger.info('[createMedicineOrder success]', data);
                ctx.body = {
                    code: 0,
                    data,
                }
            } catch (error) {
                ctx.logger.error('[createMedicineOrder ERROR]', error);
                ctx.body = {
                    code: error.code,
                    message: error.message,
                    data: error.data,
                }
            }
        }
        // json格式请求数据
        async activeInsure(ctx) {
            const { insureOrderNo }  = ctx.params
            let body = await ctx.parseBody();
            try {
                const data = await ctx.api.portalJson.activeInsure(insureOrderNo,body);
                ctx.logger.info('[activeInsure success]', data);
                ctx.body = {
                    code: 0,
                    data,
                }
            } catch (error) {
                ctx.logger.error('[activeInsure ERROR]', error);
                ctx.body = {
                    code: error.code,
                    message: error.message,
                    data: error.data,
                }
            }
        }
        // json格式请求数据
        async activeInsureQuestion(ctx) {
            const { insureOrderNo }  = ctx.params
            let body = await ctx.parseBody();
            try {
                const data = await ctx.api.portalJson.activeInsureQuestion(insureOrderNo,body);
                ctx.logger.info('[activeInsure success]', data);
                ctx.body = {
                    code: 0,
                    data,
                }
            } catch (error) {
                ctx.logger.error('[activeInsure ERROR]', error);
                ctx.body = {
                    code: error.code,
                    message: error.message,
                    data: error.data,
                }
            }
        }

        async payInsuranceOrder(ctx) {
            const { patientId, insuranceOrderId } = ctx.params;
            const { memeberId } = ctx.query;
            const body = await ctx.parseBody();
            try {
                const data = await ctx.api.portal.payInsuranceOrder(patientId, insuranceOrderId, memeberId, {
                    ...body,
                    openId: ctx.weixin.openId,
                    appId: app.config.weixin.appId,
                });
                ctx.body = {
                    code: 0,
                    data,
                }
            } catch (error) {
                ctx.body = {
                    code: error.code,
                    message: error.message,
                    data: error.data,
                }
            }
        }

        async idCardCheck(ctx) {
            try {
                const data = await ctx.api.portal.idCardCheck(ctx.query);
                ctx.body = {
                    code: 0,
                    data,
                }
            } catch (error) {
                ctx.body = {
                    code: error.code,
                    data: error.data,
                    message: error.message,
                }
            }
        }

        async getWarehouseDrugs(ctx) {
            const data = await ctx.api.portal.getWarehouseDrugs(app.config.warehouses.warehouseId, ctx.query)
            ctx.body = {
                code: 0,
                data,
            }
        }

        async createPurchaseVoucher(ctx) {
            const { patientId } = ctx.params;
            const body = await ctx.parseBody();
            const data = await ctx.api.portalJson.createPurchaseVoucher(patientId, body)
            ctx.body = {
                code: 0,
                data,
            }
        }

        async getInsuranceOrderList(ctx) {
            const { patientId } = ctx.params;
            const body = await ctx.parseBody();
            const data = await ctx.api.portal.getInsuranceOrderList(patientId, body)
            ctx.body = {
                code: 0,
                data,
            }
        }

        async getInsuranceOrderInfo(ctx) {
            const { orderId } = ctx.params;
            const data = await ctx.api.portal.getInsuranceOrderInfo(orderId)
            ctx.body = {
                code: 0,
                data,
            }
        }

        async getInsurancePayInfo(ctx) {
            const { insuranceOrderId, insuranceOrderBillId, patientId, payOrderId } = ctx.params;
            const data = await ctx.api.portal.getInsurancePayInfo(insuranceOrderId, insuranceOrderBillId, patientId, payOrderId)
            ctx.body = {
                code: 0,
                data,
            }
        }

        async updatePatientCertification(ctx) {
            const { patientId } = ctx.params;
            try {
                const data = await ctx.api.portal.updatePatientCertification(patientId, await ctx.parseBody())
                ctx.body = {
                    code: 0,
                    data,
                }
            } catch (error) {
                console.log(error);
                ctx.body = {
                    code: error.code,
                    message: error.message,
                    data: error.data,
                }
            }
        }

        async getAdsBanner(ctx) {
            const user = await ctx.api.bind.getWeixinUserInfo(ctx.weixin.openId);
            let queryParam = {};
            if (user && user.address) {
                queryParam.provinceId = user.address.provinceId;
                queryParam.cityId = user.address.cityId;
            }
            const ads = await ctx.api.bind.getAds(queryParam);
            ctx.body = {
                code: 0,
                data: ads
            }
        }

        async insuranceList(ctx) {
            const queryParam = ctx.query;
            const insuranceList = await ctx.api.bind.getInsuranceList(queryParam);
            ctx.body = {
                code: 0,
                data: insuranceList
            }
        }

        async insuranceConfigInfo(ctx) {
            const config = await ctx.api.bind.insuranceConfigInfo(ctx.params.insuranceId);
            ctx.body = {
                code: 0,
                data: config,
            }
        }
        async insuranceConfigList(ctx) {
            const query = ctx.query;
            const config = await ctx.api.bind.insuranceConfigList(query);
            ctx.body = {
                code: 0,
                data: config,
            }
        }

        async getBodyMassList(ctx) {
            const { patientId } = ctx.params;
            const data = await ctx.api.portal.getBodyMassList(patientId, ctx.query)
            ctx.body = {
                code: 0,
                data,
            }
        }

        async subBodyMass(ctx) {
            const body = await ctx.parseBody();
            const data = await ctx.api.portal.subBodyMass(body)
            ctx.body = {
                code: 0,
                data
            }
        }

        async getShareCode(ctx) {
            const data = await ctx.api.portal.getShareCode()
            ctx.body = {
                code: 0,
                data
            }
        }

        async getShareNum(ctx) {
            const body = await ctx.parseBody();
            try {
                const data = await ctx.api.portal.getShareNum(body.patientId, body.activityId)
                ctx.body = {
                    code: 0,
                    data
                }
            } catch (error) {
                app.logger.warn('[getShareNum]', error);
                ctx.body = {
                    code: error.code,
                    data: error.data,
                    message: error.message,
                }
            }

        }

        async verifyPatientInsuranceOrder(ctx) {
            const body = ctx.query;
            try {
                const data = await ctx.api.portal.verifyPatientInsuranceOrder(body)
                ctx.body = {
                    code: 0,
                    data
                }
            } catch (error) {
                console.log(error);
                ctx.body = {
                    code: error.code,
                    message: error.message,
                    data: error.data,
                }
            }

        }

        async pointExchange(ctx) {
            const list = await ctx.api.bind.pointExchange();
            ctx.body = {
                code: 0,
                data: list,
            }
        }

        async pointExchangeInfo(ctx) {
            const data = await ctx.api.bind.pointExchangeInfo(ctx.params.exchangeId);
            ctx.body = {
                code: 0,
                data: data,
            }
        }

        // async downLoadFile(ctx) {
        //     const { fileName, filepath } = ctx.query;
        //     const file = `${fileName || ''}_${new Date().getTime()}.pdf`
        //     console.log('filePath', app.config.insurance.path, file);
        //     const locationPath = path.resolve(app.config.insurance.path, `insurance`);
        //     deleteall(locationPath)
        //     fs.mkdirSync(locationPath);
        //     const fileLocation = path.resolve(locationPath, file);
        //     console.log('fileLocation', fileLocation, filepath);
        //     const writeStream = fs.createWriteStream(fileLocation)
        //     await writeFile(filepath, writeStream)
        //     this.ctx.attachment(file);
        //     this.ctx.set('Content-Type', 'octet-stream');
        //     this.ctx.body = fs.createReadStream(fileLocation);
        // }


        async cityList(ctx) {
            const data = await ctx.api.portal.getCityList();
            ctx.body = {
                code: 0,
                data,
            }
        }

        /* 保存省市 */
        async saveCity(ctx) {
            const openId = ctx.weixin.openId;
            const data = await ctx.api.bind.setWeixinUserInfo(openId, ctx.query);
            ctx.body = {
                code: 0,
                data,
            }
        }
        /* 修改签约机构 */
        async checkHospital(ctx) {
            const body = await ctx.parseBody();
            const data = await ctx.api.portal.checkHospital(body);
            if (data) {
                ctx.body = {
                    code: 0,
                    data,
                }
            } else {
                ctx.body = {
                    code: 0,
                    data: '修改失败'
                }
            }
        }
        async postNotificationForInsurance(ctx) {
            const { patientId, insuranceOrderId } = ctx.params;
            const body = await ctx.parseBody();
            const data = await ctx.api.portal.postNotificationForInsurance(patientId, insuranceOrderId, body);
            ctx.body = {
                code: 0,
                data,
            }
        }

        async getPatientsAvailable(ctx) {
            const param = ctx.query;
            const data = await ctx.api.portal.getPatientsAvailable(param);
            ctx.body = {
                code: 0,
                data,
            }
        }

        async getInusranceImgList(ctx) {
            const { insuranceId } = ctx.params;
            const data = await ctx.api.portal.getInusranceImgList(insuranceId)
            ctx.body = {
                code: 0,
                data,
            }
        }

        async getBaseDrug(ctx) {
            const data = await ctx.api.portal.getBaseDrug(ctx.query);
            ctx.body = {
                code: 0,
                data,
            }
        }

        async getDefaultDrugs(ctx) {
            const { patientId } = ctx.query;
            const data = await ctx.api.portal.getDefaultDrugs(patientId);
            ctx.body = {
                code: 0,
                data
            }
        }

        async getMedicationEvaluationList(ctx) {
            const { patientId } = ctx.query;
            const data = await ctx.api.portal.getMedicationEvaluationList(patientId);
            ctx.body = {
                code: 0,
                data
            }
        }

        async submitEvaluation(ctx) {
            const { patientId } = ctx.params;
            const body = await ctx.parseBody();
            body.drugList = JSON.parse(body.drugList)
            body.diseaseList = JSON.parse(body.diseaseList)
            const data = await ctx.api.portalJson.submitEvaluation(body, patientId);
            ctx.body = {
                code: 0,
                data
            }
        }

        async medicationEvaluation(ctx) {
            const data = await ctx.api.portal.medicationEvaluation(ctx.query);
            ctx.body = {
                code: 0,
                data
            }
        }

        async getPatientInsuranceService(ctx) {
            const data = await ctx.api.portal.getPatientInsuranceService(ctx.query.patientId);
            ctx.body = {
                code: 0,
                data
            }
        }

        /* 查询文章 */
        async getArticles(ctx) {
            const data = await ctx.api.portal.getArticles(ctx.query);
            ctx.body = {
                code: 0,
                data
            }
        }
        async getHealthDiseases(ctx) {
            const diseases = await this.ctx.api.portal.getHealthDiseases()
            ctx.body = {
                code: 0,
                data: diseases,
            };
        }

        async submitEnvironmentAssessment(ctx) {
            const body = await ctx.parseBody();
            const data = await ctx.api.portalJson.submitEnvironmentAssessment(body);
            ctx.body = {
                code: 0,
                data
            }
        }
        /* 查询文章详情 */
        async getArticleDetail(ctx) {
            // console.log("######################################",ctx.query)
            const { articleId } = ctx.query;
            const data = await ctx.api.portal.getArticleDetail(articleId);
            ctx.body = {
                code: 0,
                data
            }
        }

        async getOrderCount(ctx) {
            const data = await ctx.api.portal.getOrderCount(ctx.query.packageId);
            ctx.body = {
                code: 0,
                data
            }
        }


        async getAdpositions(ctx) {
            const data = await ctx.api.portal.getAdpositions(ctx.query.positionName);
            ctx.body = {
                code: 0,
                data
            }
        }

        async getCodeImg(ctx) {
            try {
                const data = await ctx.api.portal.getCodeImg(ctx.query.patientId);
                ctx.body = {
                    code: 0,
                    data
                }
            } catch (error) {
                ctx.body = {
                    code: error.code,
                    message: error.message,
                    data: error.data,
                }
            }
        }

        async checkForkCode(ctx) {
            try {
                const data = await ctx.api.portal.checkForkCode(ctx.query);
                ctx.body = {
                    code: 0,
                    data
                }
            } catch (error) {
                ctx.body = {
                    code: error.code,
                    message: error.message,
                    data: error.data,
                }
            }
        }

        async getCodeStatus(ctx) {
            try {
                const data = await ctx.api.portal.getCodeStatus(ctx.query.patientId);
                ctx.body = {
                    code: 0,
                    data
                }
            } catch (error) {
                ctx.body = {
                    code: error.code,
                    message: error.message,
                    data: error.data,
                }
            }
        }

        async mergePatient(ctx) {
            const body = await ctx.parseBody();
            try {
                const data = await ctx.api.portal.mergePatient(body);
                ctx.body = {
                    code: 0,
                    data
                }
            } catch (error) {
                ctx.body = {
                    code: error.code,
                    message: error.message,
                    data: error.data,
                }
            }
        }
        async getHistories(ctx) {
            try {
                const data = await ctx.api.portal.getHistories(ctx.query.id);
                if (data) {
                    ctx.body = {
                        code: 0,
                        data
                    }
                } else {
                    ctx.body = {
                        code: 0,
                        data: []
                    }
                }
            } catch (error) {
                ctx.body = {
                    code: error.code,
                    message: error.message,
                    data: error.data,
                }
            }
        }
        async getHomeInsurancelist(ctx) {
            try {
                const data = await ctx.api.portal.getHomeInsurancelist(ctx.query);
                if (data) {
                    ctx.body = {
                        code: 0,
                        data
                    }
                } else {
                    ctx.body = {
                        code: 0,
                        data: []
                    }
                }
            } catch (error) {
                ctx.body = {
                    code: error.code,
                    message: error.message,
                    data: error.data,
                }
            }
        }
        async debugDelBind(ctx) {
            try {
                await ctx.api.bind.delBindPatient('oMWpT1tbm_O5hUuVu0Sy7m8rHagQ');
                ctx.body = {
                    code: 0,
                }
            } catch (err) {
                ctx.body = {
                    code: error.code,
                    message: error.message,
                    data: error.data,
                }
            }
        }

        async getInsuranceTeamOrder(ctx) {
            try {
                const data = await ctx.api.portal.getInsuranceTeamOrder(ctx.query.patientId);
                ctx.body = {
                    code: 0,
                    data,
                }
            } catch (err) {
                ctx.body = {
                    code: error.code,
                    message: error.message,
                    data: error.data,
                }
            }
        }

        async getinsuranceCode(ctx) {
            try {
                const data = await ctx.api.portal.getinsuranceCode(ctx.query);
                ctx.body = {
                    code: 0,
                    data,
                }
            } catch (err) {
                ctx.body = {
                    code: 0,
                    message: err.message,
                    data: err.data,
                }
            }
        }
        async createYsgcuser(ctx) {
            const obj = ctx.query;
            obj.openid = ctx.weixin.openId;
            obj.appid = app.config.weixin.appId;
            try {
                const data = await ctx.api.bind.createYsgcuser(obj);
                ctx.body = {
                    code: 0,
                    data,
                }
            } catch (err) {
                ctx.body = {
                    code: 0,
                    message: err.message,
                    data: err.data,
                }
            }
        }
        async getYsgcuser(ctx) {
            const obj = ctx.query;
            try {
                const data = await ctx.api.bind.getYsgcuser(obj);
                ctx.body = {
                    code: 0,
                    data,
                }
            } catch (err) {
                ctx.body = {
                    code: 0,
                    message: err.message,
                    data: err.data,
                }
            }
        }
        async edituserInfo(ctx) {
            const body = ctx.query;
            const id = body.id;
            const estimatedPickupPeriod = body.estimatedPickupPeriod;
            const estimatedPickupDay = body.estimatedPickupDay;
            const estimatedDoctorId = body.estimatedDoctorId;
            const estimatedHospitalId = body.estimatedHospitalId;
            try {
                const data = await ctx.api.portal.edituserInfo(id, estimatedPickupPeriod, estimatedPickupDay, estimatedDoctorId, estimatedHospitalId);
                ctx.body = {
                    code: 0,
                    data: data
                }
            } catch (err) {
                ctx.body = {
                    code: 0,
                    message: err.message,
                    data: err.data,
                }
            }
            return
        }
        async doctorList(ctx) {
            const { id } = ctx.params;

            const data = await ctx.api.portal.doctorList(id);
            console.log("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@", data)
            ctx.body = {
                code: 0,
                data
            }
        }
        async mecService(ctx) {
            const { id } = ctx.params;

            const data = await ctx.api.portal.mecService(id);
            ctx.body = {
                code: 0,
                data
            }
        }
        async mecServicebind(ctx) {
            const { id, patientId } = ctx.params;
            try {
                const data = await ctx.api.portal.mecServicebind(id, patientId);
                ctx.body = {
                    code: 0,
                    data
                }
            } catch (error) {
                console.log(error);
                ctx.body = {
                    code: error.code,
                    message: error.message,
                    data: error.data,
                }
            }
        }
        async mecServicesend(ctx) {
            const { id } = ctx.params;
            try {
                const data = await ctx.api.portal.mecServicesend(id);
                ctx.body = {
                    code: 0,
                    data
                }
            } catch (error) {
                console.log(error);
                ctx.body = {
                    code: error.code,
                    message: error.message,
                    data: error.data,
                }
            }
        }
        async getInquiry(ctx) {
            const { packageId } = ctx.params;
            const data = await ctx.api.portal.getInquiry(packageId);
            ctx.body = {
                code: 0,
                data
            }
        }
        async getenquiry(ctx) {
            const { id } = ctx.params;
            const data = await ctx.api.bind.getenquiry(id);
            ctx.body = {
                code: 0,
                data
            }
        }
        async queryEnterpriseRemainAmount(ctx) {
            const { patientId } = ctx.params;
            console.log('queryEnterpriseRemainAmount patientId:', patientId)
            const data = await ctx.api.portal.queryEnterpriseRemainAmount(patientId);
            ctx.body = {
                code: 0,
                data
            }
        }

    }
    return ApiController;
};
